package com.hmall.search.service.impl;
import cn.hutool.core.bean.BeanUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import com.hmall.api.client.ItemClient;
import com.hmall.api.domain.dto.ItemDTO;
import com.hmall.api.domain.dto.PageInfo;
import com.hmall.api.domain.dto.PageQueryDTO;
import com.hmall.search.domain.dto.ItemDoc;
import com.hmall.search.service.ISearchltemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class SearchltemServicelmpl implements ISearchltemService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    //远程分页查询
    @Override
    public void initIndex() throws IOException {
        //1）分页数据  PageQueryDTO
        int page=1,
                size=1000;
        //2）执行分页查询
        do{
            PageQueryDTO pageQueryDTO = new PageQueryDTO();
            pageQueryDTO.setPageNo(page);
            pageQueryDTO.setPageSize(size);
            PageInfo<ItemDTO> pageInfo = itemClient.queryItemByPage(pageQueryDTO);
            //2.2将数据批量导入到ES
            log.info("查询到的数据：{}",pageInfo.getList());
            batchHandler(pageInfo.getList());
            //2.3翻页
            if(pageInfo.getPages()<=page){
                break;
            }
            page++;
            log.info("翻页：{}",page);
        }while(true);


    }
    //3）批量导入ES
    public void batchHandler(List<ItemDTO> items) throws IOException {
        BulkRequest.Builder builder = new BulkRequest.Builder();
        items.forEach(i->{
            builder.operations(b -> b.index(bu -> bu.index("items").id(i.getId().toString()).document(BeanUtil.toBean(i, ItemDoc.class))));
        });
        elasticsearchClient.bulk(builder.build());
    }
    //4）分页递增
}
